package com.example.demo.controller;

import com.example.demo.mapper.*;
import com.example.demo.model.Category;
import com.example.demo.model.Dish;
import com.example.demo.model.Order;
import com.example.demo.model.User;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/test")
public class TestController {

    private final CategoryMapper categoryMapper;
    private final DishMapper dishMapper;
    private final OrderMapper orderMapper;
    private final UserMapper userMapper;

    public TestController(CategoryMapper categoryMapper,
                          DishMapper dishMapper,
                          OrderMapper orderMapper,
                          UserMapper userMapper) {
        this.categoryMapper = categoryMapper;
        this.dishMapper = dishMapper;
        this.orderMapper = orderMapper;
        this.userMapper = userMapper;
    }

    /**
     * 测试数据库连接和基础查询
     * 访问: http://localhost:8088/test/db
     */
    @GetMapping("/db")
    public String testDatabaseConnection() {
        StringBuilder result = new StringBuilder();

        try {
            // 1. 测试分类表查询
            List<Category> categories = categoryMapper.findAll();
            result.append("1. 分类表测试成功，记录数: ").append(categories.size()).append("\n");

            // 2. 测试菜品表查询
            List<Dish> dishes = dishMapper.findAll();
            result.append("2. 菜品表测试成功，记录数: ").append(dishes.size()).append("\n");

            // 3. 测试订单表查询
            List<Order> orders = orderMapper.findByStatus("制作中");
            result.append("3. 订单表测试成功，'制作中'订单数: ").append(orders.size()).append("\n");

            // 4. 测试用户表查询
            User testUser = new User();
            testUser.setUserId("13800138000");
            userMapper.insert(testUser);

            User user = userMapper.findById("13800138000");
            result.append("4. 用户表测试成功，新增用户ID: ").append(user.getUserId()).append("\n");

            userMapper.delete("13800138000");
            result.append("5. 用户表删除测试成功\n");

            result.append("✅ 所有数据库测试通过！");

        } catch (Exception e) {
            result.append("❌ 测试失败: ").append(e.getMessage());
            e.printStackTrace();
        }

        return result.toString();
    }

    /**
     * 获取所有分类(JSON格式)
     * 访问: http://localhost:8088/test/categories
     */
    @GetMapping("/categories")
    public List<Category> getAllCategories() {
        return categoryMapper.findAll();
    }

    /**
     * 获取所有推荐菜品(JSON格式)
     * 访问: http://localhost:8088/test/recommended-dishes
     */
    @GetMapping("/recommended-dishes")
    public List<Dish> getRecommendedDishes() {
        return dishMapper.findRecommended();
    }
}